import axios, { AxiosRequestConfig, AxiosResponse } from 'axios'
import store, { StateAll } from '../store'
import { Toast } from 'vant'

const instance = axios.create({
    baseURL: '/api',
    timeout: 30000
})

instance.interceptors.request.use(function (config) {
    if (config.headers) {
        config.headers.authorization = 'Bearer ' + ((store.state as StateAll).users.infos?.token || '')
    }
    return config
}, function (error) {
    return Promise.reject(error)
})

instance.interceptors.response.use(function (response) {
    const { data } = response
    if (data.code === 401) {
        // token 失效
        store.commit('users/clearToken')
    } else {
        return data
    }
}, function (error) {
    const { response } = error
    const msg = response?.data?.msg

    if (msg && msg !== '服务器内部错误') Toast(msg)
    return Promise.reject(error)
})

interface Data {
    [index: string]: any
}

interface Http {
    get: (url: string, data?: Data, config?: AxiosRequestConfig) => Promise<AxiosResponse>
    post: (url: string, data?: Data, config?: AxiosRequestConfig) => Promise<AxiosResponse>
    put: (url: string, data?: Data, config?: AxiosRequestConfig) => Promise<AxiosResponse>
    patch: (url: string, data?: Data, config?: AxiosRequestConfig) => Promise<AxiosResponse>
    delete: (url: string, data?: Data, config?: AxiosRequestConfig) => Promise<AxiosResponse>
}

const http: Http = {
    get(url, data, config) {
        return instance.get(url, {
            params: data,
            ...config
        })
    },
    post(url, data, config) {
        return instance.post(url, data, config)
    },
    put(url, data, config) {
        return instance.put(url, data, config)
    },
    patch(url, data, config) {
        return instance.patch(url, data, config)
    },
    delete(url, data, config) {
        return instance.delete(url, { data, ...config })
    }
}


export default http